#include "Content.h"

Content::Content(string file) {
	std::ifstream t(file.c_str());
	std::stringstream buffer;
	buffer<<t.rdbuf();
	content = buffer.str();
}
vector<wstring> Content::split(wstring content, class Config cfg) {
	int column = floor(cfg.frame_width / cfg.font_size);
	int rows = floor(cfg.frame_height / cfg.font_size);
	int frame_blocks = column * rows;
	wstring frame_content;
	vector<wstring> frame_contents;
	int frame_sum = ceil( content.size() / frame_blocks );
	
	int i = 0;
	int position = 0;
	while(i < frame_sum) {
		frame_content = content.substr(position, frame_blocks);
		frame_contents.push_back(frame_content);
		position += frame_blocks + 1;
		++i;
	}
	if ((content.size() % frame_blocks) != 0) {//process the remainder
		frame_content = content.substr(position, content.size()-position);
		frame_contents.push_back(frame_content);
	}
	return frame_contents;
}

wstring Content::utf8_to_utf16(const string& utf8) {
	std::vector<unsigned long> unicode;
	size_t i = 0;
	while (i < utf8.size())
	{
		unsigned long uni;
		size_t todo;
		bool error = false;
		unsigned char ch = utf8[i++];
		if (ch <= 0x7F)
		{
			uni = ch;
			todo = 0;
		}
		else if (ch <= 0xBF)
		{
			throw std::logic_error("not a UTF-8 string");
		}
		else if (ch <= 0xDF)
		{
			uni = ch&0x1F;
			todo = 1;
		}
		else if (ch <= 0xEF)
		{
			uni = ch&0x0F;
			todo = 2;
		}
		else if (ch <= 0xF7)
		{
			uni = ch&0x07;
			todo = 3;
		}
		else
		{
			throw std::logic_error("not a UTF-8 string");
		}
		for (size_t j = 0; j < todo; ++j)
		{
			if (i == utf8.size())
				throw std::logic_error("not a UTF-8 string");
			unsigned char ch = utf8[i++];
			if (ch < 0x80 || ch > 0xBF)
				throw std::logic_error("not a UTF-8 string");
			uni <<= 6;
			uni += ch & 0x3F;
		}
		if (uni >= 0xD800 && uni <= 0xDFFF)
			throw std::logic_error("not a UTF-8 string");
		if (uni > 0x10FFFF)
			throw std::logic_error("not a UTF-8 string");
		unicode.push_back(uni);
	}
	std::wstring utf16;
	for (size_t i = 0; i < unicode.size(); ++i)
	{
		unsigned long uni = unicode[i];
		if (uni <= 0xFFFF)
		{
			utf16 += (wchar_t)uni;
		}
		else
		{
			uni -= 0x10000;
			utf16 += (wchar_t)((uni >> 10) + 0xD800);
			utf16 += (wchar_t)((uni & 0x3FF) + 0xDC00);
		}
	}
	return utf16;
}
